import os
from data_preprocessing import preprocess_airbnb_data
from geospatial_viz import create_3d_visualization
import plotly.io as pio
import pathlib


def save_3d_visualization(input_file, output_file):
    """生成并保存3D可视化静态图片"""
    # 确保输出目录存在
    output_dir = os.path.dirname(output_file)
    if not os.path.exists(output_dir):
        os.makedirs(output_dir, exist_ok=True)
        print(f"已创建目录: {output_dir}")

    df = preprocess_airbnb_data(input_file)
    fig = create_3d_visualization(df)

    # 保存为HTML交互式文件
    html_path = os.path.join(output_dir, 'nyc_3d_map.html')

    try:
        # 使用pathlib确保跨平台兼容性
        pathlib.Path(html_path).parent.mkdir(parents=True, exist_ok=True)
        fig.write_html(html_path)
        print(f"交互式HTML已保存至: {html_path}")
    except Exception as e:
        print(f"保存HTML时出错: {e}")

    # 保存为静态PNG图片
    try:
        pio.write_image(fig, output_file, width=1200, height=800, scale=2)
        print(f"静态图片已保存至: {output_file}")
    except Exception as e:
        print(f"保存PNG时出错: {e}")


if __name__ == "__main__":
    # 获取当前脚本所在目录
    current_dir = os.path.dirname(os.path.abspath(__file__))

    # 构建跨平台安全路径
    input_path = os.path.join(current_dir, '..', 'data', 'AB_NYC_2019.csv')
    output_dir = os.path.join(current_dir, '..', 'assets')
    output_path = os.path.join(output_dir, 'nyc_3d_map.png')

    # 标准化路径
    input_path = os.path.normpath(input_path)
    output_dir = os.path.normpath(output_dir)
    output_path = os.path.normpath(output_path)

    print("=" * 50)
    print(f"输入文件: {input_path}")
    print(f"输出目录: {output_dir}")
    print(f"输出文件: {output_path}")
    print("=" * 50)

    save_3d_visualization(input_path, output_path)